<template>
  <div class="center">
    <n-card :bordered="false" class="mt-4 proCard" size="small" :segmented="{ content: 'hard' }">
      <div class="formClass">
        <n-form :rules="rules" :model="formValue" :size="size" ref="formRef" label-placement="top">
          <n-space justify="space-between">
            <n-h6 prefix="bar" type="success">企业信息</n-h6>
            <n-space>
              <n-button v-if="type" size="small" @click="edit()">编辑</n-button>
              <n-button v-if="!type" size="small" @click="cancel()">取消</n-button>
              <n-button v-if="!type" type="success" size="small" @click="preservation">保存</n-button>
            </n-space>
          </n-space>
          <n-grid :cols="24" :x-gap="24">
            <n-form-item-gi span="8" label="姓名" path="name">
              <div v-if="!isEdit" class="detail-item-value">
                <span> {{ formValue.name }} &nbsp; </span>
              </div>
              <n-input v-if="isEdit" v-model:value="formValue.name" />
            </n-form-item-gi>
            <n-form-item-gi span="8" label="性别" path="sex">
              <div v-if="!isEdit" class="detail-item-value">
                <span> {{ (formValue.sex === '0' ? '女' : '男') }} &nbsp; </span>
              </div>
              <n-select v-model:value="formValue.sex" v-if="isEdit" :options="sexOptions" />
            </n-form-item-gi>

            <n-form-item-gi span="8" label="年龄" path="age">
              <div v-if="!isEdit" class="detail-item-value">
                <span> {{ formValue.age }} &nbsp; </span>
              </div>
              <n-input v-if="isEdit" v-model:value="formValue.age" />
            </n-form-item-gi>

            <n-form-item-gi span="8" label="联系电话" path="mobile">
              <div v-if="!isEdit" class="detail-item-value">
                <span> {{ formValue.mobile }} &nbsp; </span>
              </div>
              <n-input v-if="isEdit" v-model:value="formValue.mobile" />
            </n-form-item-gi>

            <n-form-item-gi span="8" label="身份证号" path="idCard">
              <div v-if="!isEdit" class="detail-item-value">
                <span> {{ formValue.idCard }} &nbsp; </span>
              </div>
              <n-input v-if="isEdit" v-model:value="formValue.idCard" />
            </n-form-item-gi>

            <n-form-item-gi span="8" label="身份证有效期" path="contactMobile">
              <div v-if="!isEdit" class="detail-item-value">
                <span> {{ formValue.contactMobile }} &nbsp; </span>
              </div>
              <n-input v-if="isEdit" v-model:value="formValue.contactMobile" />
            </n-form-item-gi>

            <n-form-item-gi span="8" label="户籍所在地" path="address">
              <div v-if="!isEdit" class="detail-item-value">
                <span> {{ formValue.address }} &nbsp; </span>
              </div>
              <n-input v-if="isEdit" v-model:value="formValue.address" />
            </n-form-item-gi>
          </n-grid>

          <n-space justify="space-between">
            <n-h6 prefix="bar" type="success">工作信息</n-h6>
          </n-space>
          <n-grid :cols="24" :x-gap="12">
            <n-form-item-gi span="8" label="所属企业" path="enterpriseId">
              <div v-if="!isEdit" class="detail-item-value">
                &nbsp;
                <!--                <span>-->
                <!--                  {{-->
                <!--                    industryList.length > 0 && industryList[formValue.industryId]['industryName']-->
                <!--                  }}-->
                <!--                  &nbsp;-->
                <!--                </span>-->
              </div>
              <n-select
                v-if="isEdit"
                v-model:value="formValue.enterpriseId"
                :options="enterpriseList"
              />
            </n-form-item-gi>
            <n-form-item-gi span="8" label="所属部门" path="departmentId">
<!--              <div v-if="!isEdit" class="detail-item-value">-->
<!--                &nbsp;-->
<!--                                <span>-->
<!--                                  {{-->
<!--                                    associationList.length > 0 &&-->
<!--                                    associationList[formValue.associationId]['associationName']-->
<!--                                  }}-->
<!--                                  &nbsp;-->
<!--                                </span>-->
<!--              </div>-->
<!--              <n-select-->
<!--                v-if="isEdit"-->
<!--                v-model:value="formValue.departmentId"-->
<!--                :options="associationList"-->
<!--              />-->
            </n-form-item-gi>

            <n-form-item-gi span="8" label="部门负责人" path="districtCode">
<!--              <div v-if="!isEdit" class="detail-item-value">-->
<!--                <span> {{ formValue.districtCode }} &nbsp; </span>-->
<!--              </div>-->
<!--              <n-input v-if="isEdit" v-model:value="formValue.districtCode" />-->
            </n-form-item-gi>

            <n-form-item-gi span="8" label="入职时间" path="socialCreditCode">
<!--              <div v-if="!isEdit" class="detail-item-value">-->
<!--                <span> {{ formValue.socialCreditCode }} &nbsp; </span>-->
<!--              </div>-->
<!--              <n-input v-if="isEdit" v-model:value="formValue.socialCreditCode" />-->
            </n-form-item-gi>
          </n-grid>

          <n-space justify="space-between">
            <n-h6 prefix="bar" type="success">驾驶信息</n-h6>
          </n-space>
          <n-grid :cols="24" :x-gap="12">
            <n-form-item-gi span="8" label="准驾车型" path="driverLicense.associationAgency">
              <div v-if="!isEdit" class="detail-item-value">
                <span> {{ formValue.driverLicense && formValue.driverLicense.associationAgency }} &nbsp; </span>
              </div>
              <n-input v-if="isEdit" v-model:value="formValue.driverLicense.associationAgency" />
            </n-form-item-gi>

            <n-form-item-gi span="8" label="驾驶证号" path="driverLicense.licenseNo">
              <div v-if="!isEdit" class="detail-item-value">
                <span>
                  {{ formValue.driverLicense && formValue.driverLicense.licenseNo }}&nbsp;
                </span>
              </div>
              <n-input v-if="isEdit" v-model:value="formValue.driverLicense.licenseNo" />
            </n-form-item-gi>

            <n-form-item-gi span="8" label="驾驶证档案编号" path="driverLicense.archiveNo">
              <div v-if="!isEdit" class="detail-item-value">
                <span>
                  {{ formValue.driverLicense && formValue.driverLicense.archiveNo }}&nbsp;
                </span>
              </div>
              <n-input v-if="isEdit" v-model:value="formValue.driverLicense.archiveNo" />
            </n-form-item-gi>

            <n-form-item-gi span="8" label="驾驶证有效期" path="driverLicense.licenseTimeRange">
              <div v-if="!isEdit" class="detail-item-value">
                <span>
                  {{ formValue.driverLicense && formValue.driverLicense.licenseStart && moment(formValue.driverLicense.licenseStart).format('YYYY-MM-DD') }} -
                  {{ formValue.driverLicense && formValue.driverLicense.licenseEnd && moment(formValue.driverLicense.licenseEnd).format('YYYY-MM-DD') }} &nbsp;
                </span>
              </div>
              <n-date-picker
                v-if="isEdit"
                v-model:value="driverLicense.licenseTimeRange"
                type="daterange"
                clearable
              />
            </n-form-item-gi>

            <n-form-item-gi span="8" label="驾驶证照片" path="driverLicense.licenseUri">
              <!--              :size="item.size"-->
              <n-image v-if="formValue.driverLicense && formValue.driverLicense.licensePhoto" :style="{ width: '48px' }" :src="formValue.driverLicense && formValue.driverLicense.licensePhoto" />
              <n-upload :multiple="false" @change="beforeLicenseUpload">
                <n-button>选择文件</n-button>
              </n-upload>
            </n-form-item-gi>

            <n-form-item-gi span="8" label="从业证号" path="driverJob.jobNo">
              <div v-if="!isEdit" class="detail-item-value">
                <span>
                  {{ formValue.driverJob && formValue.driverJob.jobNo }}&nbsp;
                </span>
              </div>
              <n-input v-if="isEdit" v-model:value="formValue.driverJob.jobNo" />
            </n-form-item-gi>

            <n-form-item-gi span="8" label="从业证核发地" path="driverJob.jobAddress">
              <div v-if="!isEdit" class="detail-item-value">
                <span>
                  {{ formValue.driverJob && formValue.driverJob.jobAddress }}&nbsp;
                </span>
              </div>
              <n-input v-if="isEdit" v-model:value="formValue.driverJob.jobAddress" />
            </n-form-item-gi>

            <n-form-item-gi span="8" label="从业证有效期" path="driverJob.jobRangeTime">
              <div v-if="!isEdit" class="detail-item-value">
                <span>
                  {{ formValue.driverJob && formValue.driverJob.jobStart && moment(formValue.driverJob.jobStart).format('YYYY-MM-DD') }} -
                  {{ formValue.driverJob && formValue.driverJob.jobEnd && moment(formValue.driverJob.jobEnd).format('YYYY-MM-DD') }} &nbsp;
                </span>
              </div>
              <n-date-picker
                v-if="isEdit"
                v-model:value="formValue.driverJob.jobRangeTime"
                type="daterange"
                clearable
              />
            </n-form-item-gi>

            <n-form-item-gi span="8" label="从业证照片" path="licenseUri">
              <!--              :size="item.size"-->
              <n-image v-if="formValue.driverJob && formValue.driverJob.jobPhoto" :style="{ width: '48px' }" :src="formValue.driverJob && formValue.driverJob.jobPhoto" />
              <n-upload :multiple="false" @change="beforeLicenseUpload">
                <n-button>选择文件</n-button>
              </n-upload>
            </n-form-item-gi>
          </n-grid>
        </n-form>
      </div>
    </n-card>
  </div>
</template>

<script>
  import { defineComponent, ref, onMounted, unref } from 'vue';
  import { useMessage } from 'naive-ui';
  import { NConfigProvider, NCascader, NInput, NDatePicker, NSpace } from 'naive-ui';
  import { useRoute } from 'vue-router';
  import {
    getAssoicationList,
    getDriverDetail,
    saveDriver,
    saveEnterprise
  } from "../../../api/BaseInfo";
  import { fetchIndustryList } from '../../../api/Department';
  import moment from 'moment';

  export default defineComponent({
    components: {
      NConfigProvider,
      NInput,
      NDatePicker,
      NSpace,
    },

    setup() {
      const formRef = ref(null);
      const message = useMessage();
      const route = useRoute();
      const _id = ref(route.params.id);
      const industryList = ref([]);
      const associationList = ref([]);
      const type = ref(true);
      const isEdit = ref(false);
      const formValue = ref({});
      const sexOptions = ref([
        {
          label: '女',
          value: '0',
        },
        {
          label: '男',
          value: '1',
        },
      ]);
      const beforeLicenseUpload = ({ fileList }) => {
        const file = fileList[fileList.length - 1].file;
        formValue.value.licensePhoto = file;
      };
      //编辑
      const edit = () => {
        type.value = false;
        isEdit.value = true;
        ItemList.value.map((res) => {
          return (res.disabled = false);
        });
        console.log(formValue.value);
      };
      //保存
      const preservation = (e) => {
        e.preventDefault();
        formRef.value.validate(async (error) => {
          console.log(formValue.value.licenseTimeRange);
          if (error) return; // 验证失败
          formValue.value.licenseStart = moment(formValue.value.licenseTimeRange[0]).format(
            'YYYY-MM-DD'
          );
          formValue.value.licenseEnd = moment(formValue.value.licenseTimeRange[1]).format(
            'YYYY-MM-DD'
          );
          const keys = Object.keys(formValue.value);
          const formdata = new FormData();
          for (let i = 0; i < keys.length; i++) {
            const key = keys[i];
            const value = formValue.value[key];
            if (value.hasOwnProperty('driverLicense')) {
              //  这里进行驾驶员信息处理
              const driverLicenseKeys = Object(value.driverLicense);
              for (let licenseIndex = 0; licenseIndex < driverLicenseKeys.length; licenseIndex++) {
                const licenseKey = driverLicenseKeys[licenseIndex];
                const licenseValue = value.driverLicense[licenseKey];
              }
            }
            if (value.hasOwnProperty('driverJob')) {
              //  这里进行从业信息处理
              const driverJobsKeys = Object(value.driverJob);
              for (let jobIndex = 0; jobIndex < driverJobsKeys.length; jobIndex++) {
                const jobKey = driverJobsKeys[jobIndex];
                const jobValue = value.driverJob[jobKey];
                // formdata.append(key)
              }
            }
            if (key !== 'createTime' && key !== 'licenseTimeRange' && key !== 'updateTime') {
              formdata.append(key, formValue.value[key]);
            }
          }
          const res = await saveDriver(formdata);
          // const res = await saveEnterprise(formdata);
          // 保存完成之后重新设置为disabled
          type.value = true;
          isEdit.value = false;
          ItemList.value.map((res) => {
            return (res.disabled = true);
          });
        });
      };
      //取消
      const cancel = () => {
        type.value = true;
        isEdit.value = false;
        ItemList.value.map((res) => {
          return (res.disabled = true);
        });
      };
      // getEnterpriseDetail
      onMounted(async () => {
        const record = await getDriverDetail(_id.value);
        formValue.value = record;
        formValue.value.sex = formValue.value.sex.toString();
        // formValue.value.licenseTimeRange = ref([
        //   Date.parse(record.licenseStart),
        //   Date.parse(record.licenseEnd),
        // ]);
        // record.createTime = Date.parse(record.createTime);
        industryList.value = await fetchIndustryList();
        associationList.value = await getAssoicationList();
        associationList.value = associationList.value.list;
        for (let i = 0; i < associationList.value.length; i++) {
          const item = associationList.value[i];
          associationList.value[i].label = item.associationName;
          associationList.value[i].value = item.id;
        }
        for (let i = 0; i < industryList.value.length; i++) {
          const item = industryList.value[i];
          industryList.value[i].label = item.industryName;
          industryList.value[i].value = item.id;
        }
      });
      return {
        sexOptions,
        moment,
        beforeLicenseUpload,
        industryList,
        associationList,
        formRef,
        isEdit,
        edit,
        preservation,
        cancel,
        size: ref('medium'),
        formValue,
        type,
        rules: {
          legalMobile: {
            required: true,
            message: '请输入手机号',
            trigger: ['input'],
          },
          legalPerson: {
            required: true,
            message: '请输入企业法人',
            trigger: ['input'],
          },
          industryId: {
            required: true,
            message: '请选择所属行业',
            trigger: ['input', 'blur'],
          },
          enterpriseName: {
            required: true,
            message: '请输入企业名称',
            trigger: ['input'],
          },
          districtCode: {
            required: true,
            message: '请选择区域',
            trigger: ['input', 'blur'],
          },
          contactPerson: {
            required: true,
            message: '请输入联系人',
            trigger: ['input'],
          },
          contactMobile: {
            required: true,
            message: '请输入联系人手机号',
            trigger: ['input'],
          },
        },
      };
    },
  });
</script>
<style lang="less" scoped>
  .center :deep .n-avatar {
    position: relative;
    bottom: 15px;
  }
  .formClass {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .detail-item-value {
    background-color: #f5f5f5;
    padding: 5px 12px;
    width: 100%;
  }
</style>
